package com.vehicle.auto.click.test;

import java.awt.image.BufferedImage;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Point;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class LaunchFireFox {
    public static void main(String[] args) throws Exception {
        System.out.println("start selenium");
        System.setProperty("webdriver.firefox.bin", "D:\\MySoft\\firefox\\firefox.exe");
        System.setProperty("webdriver.gecko.driver", "D:\\yankong_tool\\geckodriver.exe");
        WebDriver driver = new FirefoxDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(8L, TimeUnit.SECONDS);
        driver.get("http://www.xycq.online/forum/logging.php?action=login");
        List img = driver.findElements(By.xpath("//*[@id=\"seccode\"]"));

        for(int i = 0; i < img.size(); ++i) {
            downloadYanZhengMa((WebElement)img.get(i), driver);
        }

    }

    private static String downloadYanZhengMa(WebElement ele, WebDriver _driver) throws Exception {
        File screenshot = (File)((TakesScreenshot)_driver).getScreenshotAs(OutputType.FILE);
        BufferedImage fullImg = ImageIO.read(screenshot);
        Point point = ele.getLocation();
        int eleWidth = ele.getSize().getWidth();
        int eleHeight = ele.getSize().getHeight();
        BufferedImage eleScreenshot = fullImg.getSubimage(point.getX() + 8, point.getY() + 4, eleWidth, eleHeight);
        ImageIO.write(eleScreenshot, "png", screenshot);
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String filename = "yanzhengma/yanzhengma_" + df.format(new Date()) + ".png";
        File screenshotLocation = new File(filename);
        FileUtils.copyFile(screenshot, screenshotLocation);
        return filename;
    }

    public void testScreenshoutByTakesScreenshot() {
    }
}
